package cn.pet.service.manage.auth;

import cn.pet.service.manage.context.GlobalContext;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtRequestFilter extends OncePerRequestFilter {

    final JWTUtil jwtUtil;

    final MyAuthenticationProvider myAuthenticationProvider;

    public JwtRequestFilter(JWTUtil jwtUtil, MyAuthenticationProvider myAuthenticationProvider) {
        this.jwtUtil = jwtUtil;
        this.myAuthenticationProvider = myAuthenticationProvider;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authorizationHeader = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
        String userId = null;
        String jwtToken = null;
        if(authorizationHeader!=null && authorizationHeader.startsWith("Bearer ")){
            jwtToken = authorizationHeader.substring(7);
            try {
                userId = jwtUtil.getUserId(jwtToken);
            }catch (TokenExpiredException tokenExpiredException){
                log.error("JWT Token has expired.");
            }catch (Exception err){
                log.error("JWT Token error: {}", err.getMessage(), err);
            }
        }

        if(userId!=null && SecurityContextHolder.getContext().getAuthentication()==null){
            String token = GlobalContext.get(Integer.parseInt(userId));
            if(token !=null && !jwtUtil.isTokenExpired(token)){
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the Spring Security Configurations successfully.
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(myAuthenticationProvider.getUserInfo(Integer.parseInt(userId)), null, null);
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
